"""
---------------------------------------------------------------------
- File: users.py
- Date: 2025/11/5
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 系统用户相关API
---------------------------------------------------------------------
"""

from fastapi import APIRouter, Path, Depends, HTTPException, Query

from app.core.dependency import get_current_user
from app.core.dependency import get_service_dependency
# response
from app.core.response import ResponseBase, ResponseSuccess, standard_response
from app.models.system import Users
from app.schemas.system.users import UserRead, UserCreate, UserUpdate, UserWithRoles
from app.service.service_users import ServiceUsers

ServiceUsers = get_service_dependency(ServiceUsers)

users_router = APIRouter(
    prefix="/system/users",
    tags=["系统管理-用户管理"],
    dependencies=[Depends(get_current_user)],
    responses=standard_response,
)


@users_router.get("/user_roles", summary="获取角色与用户信息列表", response_model=ResponseBase[list[UserWithRoles]])
async def get_user_roles(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(3, le=50, description="每页数量"),
    service_users: ServiceUsers = Depends(),
):
    """
    返回角色信息及与角色关联的用户信息
    """
    result = await service_users.get_multi_userWithRoles(skip=(page - 1) * size, limit=size)
    return ResponseSuccess(data=result)


@users_router.get("/{user_id}", summary="获取某一用户信息", response_model=ResponseBase[UserRead])
async def get_user(user_id: int = Path(..., description="用户ID"), service_users: ServiceUsers = Depends()):
    """
    根据用户ID获取用户信息
    """
    user = await service_users.get(id=user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    return ResponseSuccess(data=user)


@users_router.post("/", summary="创建用户信息", response_model=ResponseBase[UserRead])
async def create_user(user_in: UserCreate, service_users: ServiceUsers = Depends()):
    """
    创建用户信息
    """
    existing_user = await service_users.get_existing_user(user_in=user_in)
    if existing_user:
        if existing_user.user_no == user_in.user_no:
            raise HTTPException(status_code=400, detail="用户编号已存在,请更换")
        if existing_user.user_name == user_in.user_name:
            raise HTTPException(status_code=400, detail="用户名已存在,请更换")
        if existing_user.user_email == user_in.user_email:
            raise HTTPException(status_code=400, detail="用户邮箱已存在,请更换")
        if existing_user.user_phone == user_in.user_phone:
            raise HTTPException(status_code=400, detail="用户手机号已存在,请更换")
        raise HTTPException(status_code=400, detail="用户信息已存在,请更换")

    user = await service_users.create(obj_in=user_in)
    return ResponseSuccess(data=user)


@users_router.get("/", summary="获取用户列表", response_model=ResponseBase[list[UserRead]])
async def get_users(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(3, le=100, description="每页数量"),
    service_users: ServiceUsers = Depends(),
):
    """
    获取用户信息列表
    """
    users = await service_users.get_multi(skip=(page - 1) * size, limit=size)
    if users is None:
        users = []
    return ResponseSuccess(data=users)


@users_router.patch("/{user_id}", summary="更新用户信息", response_model=ResponseBase[UserRead])
async def update_user(
    user_in: UserUpdate, user_id: int = Path(..., description="用户ID"), service_users: ServiceUsers = Depends()
):
    """
    根据用户ID更新用户信息
    """
    user = await service_users.get(id=user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    user = await service_users.update(db_obj=user, obj_in=user_in)
    return ResponseSuccess(data=user)


@users_router.delete("/{user_id}", summary="删除用户信息", response_model=ResponseBase[UserRead])
async def delete_user(user_id: int = Path(..., description="用户ID"), service_users: ServiceUsers = Depends()):
    """
    根据用户ID删除用户信息
    """
    user: Users | None = await service_users.get(id=user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")

    if user.user_no == "admin":
        raise HTTPException(status_code=400, detail="不能删除管理员用户")
    db_user = await service_users.remove(id=user_id)

    if db_user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    return ResponseSuccess(data=db_user)
